package pl.gladiator.ftp;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.io.CopyStreamAdapter;
import org.apache.commons.net.io.Util;

import pl.gladiator.model.Gallery;

public class FTPManager {

	final FTPClient ftp = new FTPClient();
	boolean connect = false;
	public final static String directory = "gladiator";

	public void connectToFTPServer() {
		// final String adresSerweru = "ftp.yoyo.pl";
		// final String uzytkownik = "rspkca.yoyo.pl";
		// final String haslo = "asdasd1";

		final String adresSerweru = "ftp.misiekmk.linuxpl.info";
		final String uzytkownik = "misiekmk";
		final String haslo = "stfzv6095";
		int reply;
		try {
			ftp.connect(adresSerweru);
			System.out.println("Polaczono z serwerem.");
			System.out.print(ftp.getReplyString());

			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				System.err.println("FTP server refused connection.");
				connect = true;
			}
			if (!ftp.login(uzytkownik, haslo)) {
				System.out.print(ftp.getReplyString());
				ftp.logout();
			} else {
				System.out.print(ftp.getReplyString());

				ftp.setFileType(FTP.BINARY_FILE_TYPE);
				System.out.print(ftp.getReplyString());

				ftp.enterLocalPassiveMode();
				System.out.print("Enter local passive mode.\n");
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void disconnectFromFTP() {
		try {
			System.out.print(ftp.getReplyString());
			if (ftp.isConnected()) {
				ftp.logout();
				ftp.disconnect();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void upload(File uploadFile, String nazwa){
	    try {
	    	if (uploadFile.exists()) {
            	System.out.println("Uploading file... "+uploadFile.getName());
                FileInputStream fis = new FileInputStream(uploadFile);
                
                OutputStream ftpOut = ftp.storeFileStream(uploadFile.getName());
                OutputStream output = new BufferedOutputStream(ftpOut);
                System.out.print(ftp.getReplyString());
                Util.copyStream(fis, output, ftp.getBufferSize(), uploadFile.length(), 
                new CopyStreamAdapter(){
                	public void bytesTransferred(
                			long totalBytesTransferred, int bytesTransferred, long streamSize) {
                     }
                });
               
                fis.close();
                output.close();
                if (!ftp.completePendingCommand()) {
                   System.out.println("Failed to copy file thru FTP: completePendingCommand failed.");
                   System.out.print(ftp.getReplyString());
                }
               
                
            } else {
            	System.out.println("Not uploading file, because it doesn't exists.");
            }
		} catch (IOException e) {
			e.printStackTrace();
		}
	}  
	
	public void createDirectory(String katalog){
		boolean cd;
		try {
			cd = ftp.changeWorkingDirectory(katalog);
			System.out.print(ftp.getReplyString());
	        
	        if (!cd) {
	        	boolean mkdir = ftp.makeDirectory(katalog);
	            System.out.print(ftp.getReplyString());
	            if (!mkdir) {
	            	System.err.println("Cannot create upload directory: " + katalog + " at server: ");
	            }
	            cd = ftp.changeWorkingDirectory(katalog);
	        }
		} catch (IOException e) {
			e.printStackTrace();
		}
    	
	}

	public FTPFile[] showPicturesFromAlbum(String katalog) {

		FTPFile[] files = null;
		try {
			files = ftp.listFiles("/" + directory + "/" + katalog);
			System.out.print(ftp.getReplyString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return files;

	}

	public FTPFile[] showAlbums() {
		FTPFile[] directories = null;
		try {
			directories = ftp.listDirectories("/" + directory);
			System.out.print(ftp.getReplyString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return directories;
	}

	public List<Gallery> getAlbumsNames() {
		final FTPManager ftp = new FTPManager();
		final List<Gallery> albumList = new ArrayList<Gallery>();
		ftp.connectToFTPServer();
		FTPFile[] list = ftp.showAlbums();
		if (list != null) {
			for (FTPFile ftpFile : list) {
				if (ftpFile.getName().equals(".")
						|| ftpFile.getName().equals("..")) {
				} else {
					Gallery gallery = new Gallery();
					gallery.setAlbumName(ftpFile.getName());
					albumList.add(gallery);
				}
			}
		}
		ftp.disconnectFromFTP();
		return albumList;

	}

	public List<Gallery> getFileNamesFromAlbum(String albumName) {
		final FTPManager ftp = new FTPManager();
		final List<Gallery> fileList = new ArrayList<Gallery>();
		ftp.connectToFTPServer();
		FTPFile[] list = ftp.showPicturesFromAlbum(albumName);
		if (list != null) {
			for (FTPFile ftpFile : list) {
				if (ftpFile.getName().equals(".")
						|| ftpFile.getName().equals("..")) {
				} else {
					Gallery gallery = new Gallery();
					String path = albumName + "/" + ftpFile.getName();
					gallery.setPath(path);
					fileList.add(gallery);
				}
			}
		}
		ftp.disconnectFromFTP();
		return fileList;

	}

	// public static void main(String[] args) {
	// FTPManager ftp = new FTPManager();
	// ftp.connectToFTPServer();
	// ftp.pokazKatalogiNaSerwerze();
	// // FTPFile[] listaZdjec = ftp.showPicturesFromAlbum("zdjeciaProfilowe");
	// // for (FTPFile ftpFile : listaZdjec) {
	// // System.out.println(ftpFile.getName());
	// // }
	// for (FTPFile ftpFile : ftp.pokazKatalogiNaSerwerze()) {
	// System.out.println(ftpFile.getName());
	// }
	// }
}
